"""
使用http.client发送http请求，使用这个原因1个是原生python支持，另一个是减少多余的封装
"""
import http.client
import urllib


def get(host, url, headers=None, timeout=3,data={}):
    conn = http.client.HTTPConnection(host, timeout=timeout)
    conn.request("get", url, headers,data)
    response = conn.getresponse()
    if response.status != 200:
        print(f"Status: {response.status}, Reason: {response.reason}")
        return response.read().decode("utf-8")


def post_form(host, url, headers=None, timeout=3,data={}):

    with http.client.HTTPSConnection(host, timeout=timeout) as conn:
        try:
            # 构造表单数据
            form_data = urllib.parse.urlencode({"title": "foo", "body": "bar", "userId": 1})
            headers = {"Content-Type": "application/x-www-form-urlencoded"}

            # 发送 POST 请求
            conn.request("POST", "/posts", body=form_data, headers=headers)

            # 获取响应
            response = conn.getresponse()
            print(f"Status: {response.status}, Reason: {response.reason}")
            data = response.read().decode("utf-8")
            print("Response Data:", data)
        except Exception as e:
            print("Error:", e)
